import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import Layout from "@/layout/index.vue";
import { getToken } from "@/utils/auth";
import { useUserStore } from "@/stores/user";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
    meta: {
      title: "登录",
      hidden: true,
    },
  },
  {
    path: "/",
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("@/views/dashboard/index.vue"),
        meta: {
          title: "dashboard",
          icon: "House",
          permission: "/dashboard",
        },
      },
    ],
  },
  {
    path: "/system",
    component: Layout,
    meta: {
      title: "系统管理",
      icon: "Operation",
      permission: "/system",
    },
    children: [
      {
        path: "user",
        name: "User",
        component: () => import("@/views/system/user/index.vue"),
        meta: {
          title: "用户管理",
          icon: "User",
          permission: "/system/user",
        },
      },
      {
        path: "role",
        name: "Role",
        component: () => import("@/views/system/role/index.vue"),
        meta: {
          title: "角色管理",
          icon: "UserFilled",
          permission: "/system/role",
        },
      },
      {
        path: "menu",
        name: "Menu",
        component: () => import("@/views/system/menu/index.vue"),
        meta: {
          title: "菜单管理",
          icon: "Menu",
          permission: "/system/menu",
        },
      },
    ],
  },
  {
    path: "/order",
    component: Layout,
    meta: {
      title: "订单管理",
      icon: "Shop",
      permission: "/order",
    },
    children: [
      {
        path: "recordpay",
        name: "OrderRecordpay",
        component: () => import("@/views/recordpay/list.vue"),
        meta: {
          title: "资金记录",
          icon: "Money",
          permission: "/order/recordpay",
        },
      },
      {
        path: "usdt",
        name: "OrderUsdt",
        component: () => import("@/views/income/usdtlist.vue"),
        meta: {
          title: "USDT入金",
          icon: "Coin",
          permission: "/order/usdt",
        },
      },
      {
        path: "bank",
        name: "OrderBank",
        component: () => import("@/views/income/banklist.vue"),
        meta: {
          title: "银行卡入金",
          icon: "CreditCard",
          permission: "/order/bank",
        },
      },
      {
        path: "outusdt",
        name: "OutUsdt",
        component: () => import("@/views/usdt/list.vue"),
        meta: {
          title: "USDT出金",
          icon: "CreditCard",
          permission: "/order/outusdt",
        },
      },
    ],
  },
  {
    path: "/paymentConfig",
    component: Layout,
    meta: {
      title: "渠道配置",
      icon: "Tools",
      permission: "/paymentConfig",
    },
    children: [
      {
        path: "list",
        name: "PaymentConfigList",
        component: () => import("@/views/paymentConfig/list.vue"),
        meta: {
          title: "渠道列表",
          icon: "Tools",
          permission: "/paymentConfig/list",
        },
      },
      {
        path: "relation",
        name: "PaymentConfigRelation",
        component: () => import("@/views/paymentConfig/relation.vue"),
        meta: {
          title: "渠道-用户列表",
          icon: "List",
          permission: "/paymentConfig/relation",
        },
      },
    ],
  },

  {
    path: "/docking",
    component: Layout,
    meta: {
      title: "对接信息",
      icon: "Connection",
      permission: "/docking/info",
    },
    children: [
      {
        path: "info",
        name: "DockingInfo",
        component: () => import("@/views/docking/info.vue"),
        meta: {
          title: "对接信息",
          icon: "Link",
          permission: "/docking/info",
        },
      },
    ],
  },

  {
    path: "/action",
    component: Layout,
    meta: {
      title: "操作日志",
      icon: "Document",
      permission: "/action",
    },
    children: [
      {
        path: "list",
        name: "ActionList",
        component: () => import("@/views/action/list.vue"),
        meta: {
          title: "操作日志",
          icon: "List",
          permission: "/action/list",
        },
      },
    ],
  },

  // 添加一个WEB配置菜单，路径是/webconfig,子路由的路径也是webconfig
  {
    path: "/webconfig",
    component: Layout,
    meta: {
      title: "WEB配置",
      icon: "Monitor",
      permission: "/webconfig",
    },
    children: [
      {
        path: "list",
        name: "WebconfigList",
        component: () => import("@/views/webconfig/list.vue"),
        meta: {
          title: "WEB配置",
          icon: "Monitor",
          permission: "/webconfig/list",
        },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 后台管理系统`;
  }

  // 简单的登录验证（实际项目中应该检查token等）
  const token = getToken();

  if (to.path !== "/login" && !token) {
    next("/login");
    return;
  }

  // 如果已登录且访问的不是登录页，检查权限
  if (token && to.path !== "/login") {
    const userStore = useUserStore();

    // 确保用户信息已加载
    if (!userStore.userInfo && token) {
      try {
        await userStore.fetchUserInfo();
      } catch (error) {
        console.error("获取用户信息失败:", error);
        next("/login");
        return;
      }
    }

    // 如果路由需要权限验证
    if (to.meta?.permission) {
      if (!userStore.hasPermission(to.meta.permission as string)) {
        // 没有权限，跳转到首页或显示无权限页面
        next("/dashboard");
        return;
      }
    }
  }

  next();
});

export default router;
